// Kony


#include "AbilitySystem/BaseAbilitySystemLibrary.h"

#include "AbilitySystemBlueprintLibrary.h"
#include "AbilitySystemComponent.h"
#include "BaseAbilityTypes.h"
#include "BaseGameplayTags.h"
#include "AbilitySystem/Data/AbilityInfo.h"
#include "Game/Base_GameModeBase.h"
#include "Game/LoadScreenSaveGame.h"
#include "Interaction/CombatInterface.h"
#include "Interaction/PlayerInterface.h"
#include "Kismet/GameplayStatics.h"
#include "Player/BasePlayerState.h"
#include "UI/HUD/BaseHUD.h"
#include "UI/WidgetController/BaseWidgetController.h"

bool UBaseAbilitySystemLibrary::MakeWidgetControllerParams(const UObject* WorldContextObject, FWidgetControllerParams& OutWCParams, ABaseHUD*& OutBaseHUD)
{
	//获取玩家控制器
	if (APlayerController* PC = UGameplayStatics::GetPlayerController(WorldContextObject, 0))
	{
		OutBaseHUD = Cast<ABaseHUD>(PC->GetHUD());
		if (OutBaseHUD)
		{
			//获取玩家状态
			ABasePlayerState* PS = PC->GetPlayerState<ABasePlayerState>();
			//获取玩家能力组件
			UAbilitySystemComponent* ASC = PS->GetAbilitySystemComponent();
			//获取玩家属性组件
			UAttributeSet* AS = PS->GetAttributeSet();
			//用上面这些组件 填入到小组件控制器参数中
			OutWCParams.AttributeSet = AS;
			OutWCParams.AbilitySystemComponent = ASC;
			OutWCParams.PlayerState = PS;
			OutWCParams.PlayerController = PC;
			return true;
		}
	}
	return false;
}

UOverlayWidgetController* UBaseAbilitySystemLibrary::GetBaseOverlayWidgetController(const UObject* WorldContextObject)
{
	//创建引用传递控制器参数 接收函数里赋值的数据
	FWidgetControllerParams WCParams;
	//创建引用传递HUD指针 接收函数里赋值的数据
	ABaseHUD* BaseHUD = nullptr;
	//获取小组件控制器参数和HUD并赋值到上面的变量中，成功返回true
	if (MakeWidgetControllerParams(WorldContextObject,WCParams,BaseHUD))
	{
		return BaseHUD->GetOverlayWidgetController(WCParams);
	}
	return nullptr;
}

UAttributeMenuWidgetController* UBaseAbilitySystemLibrary::GetBaseAttributeMenuWidgetController(const UObject* WorldContextObject)
{
	//创建引用传递控制器参数 接收函数里赋值的数据
	FWidgetControllerParams WCParams;
	//创建引用传递HUD指针 接收函数里赋值的数据
	ABaseHUD* BaseHUD = nullptr;
	//获取小组件控制器参数和HUD并赋值到上面的变量中，成功返回true
	if (MakeWidgetControllerParams(WorldContextObject,WCParams,BaseHUD))
	{
		return BaseHUD->GetAttributeMenuWidgetController(WCParams);
	}
	return nullptr;
}

USpellMenuWidgetController* UBaseAbilitySystemLibrary::GetBaseSpellMenuWidgetController(const UObject* WorldContextObject)
{
	//创建引用传递控制器参数 接收函数里赋值的数据
	FWidgetControllerParams WCParams;
	//创建引用传递HUD指针 接收函数里赋值的数据
	ABaseHUD* BaseHUD = nullptr;
	//获取小组件控制器参数和HUD并赋值到上面的变量中，成功返回true
	if (MakeWidgetControllerParams(WorldContextObject,WCParams,BaseHUD))
	{
		return BaseHUD->GetSpellMenuWidgetController(WCParams);
	}
	return nullptr;
}

void UBaseAbilitySystemLibrary::InitializeDefaultAttributes(const UObject* WorldContextObject,ECharacterClass CharacterClass, float Level,UAbilitySystemComponent* ASC)
{
	//从游戏模式 获取角色类属性系数配置信息
	UCharacterClassInfo* CharacterClassInfo = GetCharacterClassInfo(WorldContextObject);
	if (CharacterClassInfo == nullptr) return;
	// 从能力系统组件中获取当前的角色Avatar（玩家控制的角色实例）
	AActor* AvatarActor = ASC->GetAvatarActor();
	//获取到类中的主要属性结构体
	FCharacterClassDefaultInfo ClassDefaultInfo = CharacterClassInfo->GetCharacterClassDefaultInfo(CharacterClass);

	//获取主要属性并赋值到能力上下文句柄
	FGameplayEffectContextHandle PrimaryAttributesContextHandle = ASC->MakeEffectContext();
	//把玩家控制的角色实例添加到能力上下文句柄 这个是避免计算血量报错
	PrimaryAttributesContextHandle.AddSourceObject(AvatarActor);
	//获取主要属性并赋值到能力规格句柄
	const FGameplayEffectSpecHandle PrimaryAttributesSpecHandle = ASC->MakeOutgoingSpec(ClassDefaultInfo.PrimaryAttributes, Level,PrimaryAttributesContextHandle);
	//把获取的主要属性，应用到游戏能力组件
	ASC->ApplyGameplayEffectSpecToSelf(*PrimaryAttributesSpecHandle.Data.Get());

	//获取主要属性并赋值到能力上下文句柄
	FGameplayEffectContextHandle SecondaryAttributesContextHandle = ASC->MakeEffectContext();
	SecondaryAttributesContextHandle.AddSourceObject(AvatarActor);
	const FGameplayEffectSpecHandle SecondaryAttributesSpecHandle = ASC->MakeOutgoingSpec(CharacterClassInfo->SecondaryAttributes_Enemy, Level,SecondaryAttributesContextHandle);
	ASC->ApplyGameplayEffectSpecToSelf(*SecondaryAttributesSpecHandle.Data.Get());


	//获取核心属性并赋值到能力上下文句柄
	FGameplayEffectContextHandle VitalAttributesContextHandle = ASC->MakeEffectContext();
	VitalAttributesContextHandle.AddSourceObject(AvatarActor);
	const FGameplayEffectSpecHandle VitalAttributesSpecHandle = ASC->MakeOutgoingSpec(CharacterClassInfo->VitalAttributes, Level,VitalAttributesContextHandle);
	ASC->ApplyGameplayEffectSpecToSelf(*VitalAttributesSpecHandle.Data.Get());
}
//从存档中读取主属性 初始化主属性信息
void UBaseAbilitySystemLibrary::InitializeDefaultAttributesFromSaveData(const UObject* WorldContextObject,UAbilitySystemComponent* ASC, ULoadScreenSaveGame* SaveGame)
{
	//从游戏模式 获取角色类属性系数配置信息
	UCharacterClassInfo* CharacterClassInfo = GetCharacterClassInfo(WorldContextObject);
	if (CharacterClassInfo == nullptr) return;
	// 从能力系统组件中获取当前的角色Avatar（玩家控制的角色实例）
	// AActor* AvatarActor = ASC->GetAvatarActor();
	const FBaseGameplayTags& GameplayTags = FBaseGameplayTags::Get();
	//从源技能系统组件中获取源角色
	const AActor* SourceAvatarActor = ASC->GetAvatarActor();
	//从源能力系统组件中获取游戏效果上下文句柄
	FGameplayEffectContextHandle EffectContextHandle = ASC->MakeEffectContext();
	//给效果上下文添加源对象
	EffectContextHandle.AddSourceObject(SourceAvatarActor);
	
	//创建游戏效果规格句柄 - 通过主属性的设置值数据资产
	const FGameplayEffectSpecHandle SpecHandle = ASC->MakeOutgoingSpec(CharacterClassInfo->PrimaryAttributes_SetByCaller,1.f,EffectContextHandle);

	//通过异常伤害类型标签调用时 触发对应标签的 技能基础伤害 （这个就是技能伤害） 可以用这个去计算百分比
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Attributes_Primary_Strength,SaveGame->Strength); //力量
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Attributes_Primary_Intelligence,SaveGame->Intelligence); //智力
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Attributes_Primary_SoulPower,SaveGame->SoulPower); //魂力
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Attributes_Primary_Agility,SaveGame->Agility); //敏捷
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Attributes_Primary_Spirit,SaveGame->Spirit); //神识
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Attributes_Primary_Resilience,SaveGame->Resilience); //经脉
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Attributes_Primary_Vigor,SaveGame->Vigor); //体魄
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Attributes_Primary_Insight,SaveGame->Insight); //心境
	//应用游戏效果到自身
	ASC->ApplyGameplayEffectSpecToSelf(*SpecHandle.Data.Get());

	/* 应用次要属性游戏效果更新 */
	//获取主要属性并赋值到能力上下文句柄
	FGameplayEffectContextHandle SecondaryAttributesContextHandle = ASC->MakeEffectContext();
	SecondaryAttributesContextHandle.AddSourceObject(SourceAvatarActor);
	const FGameplayEffectSpecHandle SecondaryAttributesSpecHandle = ASC->MakeOutgoingSpec(CharacterClassInfo->SecondaryAttributes_Infinite, 1.f,SecondaryAttributesContextHandle);
	ASC->ApplyGameplayEffectSpecToSelf(*SecondaryAttributesSpecHandle.Data.Get());
	//获取核心属性并赋值到能力上下文句柄
	FGameplayEffectContextHandle VitalAttributesContextHandle = ASC->MakeEffectContext();
	VitalAttributesContextHandle.AddSourceObject(SourceAvatarActor);
	const FGameplayEffectSpecHandle VitalAttributesSpecHandle = ASC->MakeOutgoingSpec(CharacterClassInfo->VitalAttributes, 1.f,VitalAttributesContextHandle);
	ASC->ApplyGameplayEffectSpecToSelf(*VitalAttributesSpecHandle.Data.Get());
}

//初始化敌人能力
void UBaseAbilitySystemLibrary::GvieStartupAbilities(const UObject* WorldContextObject, UAbilitySystemComponent* ASC, ECharacterClass CharacterClass)
{
	//获取类型数据类
	UCharacterClassInfo* CharacterClassInfo = GetCharacterClassInfo(WorldContextObject);
	if (CharacterClassInfo == nullptr) return;
	//遍历通用能力 可以赋予比如 受击反应、死亡效果 等
	for (TSubclassOf<UGameplayAbility> AbilityClass : CharacterClassInfo->CommonAbilities)
	{
		//获取能力规格
		FGameplayAbilitySpec AbilitySpec = FGameplayAbilitySpec(AbilityClass,1);
		//赋予激活能力
		ASC->GiveAbility(AbilitySpec);
	}
	//获取角色职业默认信息
	const FCharacterClassDefaultInfo& DefaultInfo = CharacterClassInfo->GetCharacterClassDefaultInfo(CharacterClass);
	//遍历怪物的启动能力 比如近战攻击能力
	for (TSubclassOf<UGameplayAbility> AbilityClass : DefaultInfo.StartupAbilities)
	{
		if (ASC->GetAvatarActor()->Implements<UCombatInterface>())
		{
			FGameplayAbilitySpec AbilitySpec = FGameplayAbilitySpec(AbilityClass,ICombatInterface::Execute_GetPlayerLevel(ASC->GetAvatarActor()));
			ASC->GiveAbility(AbilitySpec);
		}
	}
}
//设置获取角色各类信息参数 用于获取给角色设置的各种属性和伤害相关曲线系数表
UCharacterClassInfo* UBaseAbilitySystemLibrary::GetCharacterClassInfo(const UObject* WorldContextObject)
{
	const ABase_GameModeBase* Base_GameMode = Cast<ABase_GameModeBase>(UGameplayStatics::GetGameMode(WorldContextObject));
	if (Base_GameMode == nullptr) return nullptr;
	return Base_GameMode->CharacterClassInfo;
}
//获取能力信息,这里是通过游戏模式获取设置的能力信息（也就是角色都有哪些能力）
UAbilityInfo* UBaseAbilitySystemLibrary::GetAbilityInfo(const UObject* WorldContextObject)
{
	const ABase_GameModeBase* Base_GameMode = Cast<ABase_GameModeBase>(UGameplayStatics::GetGameMode(WorldContextObject));
	if (Base_GameMode == nullptr) return nullptr;
	return Base_GameMode->AbilityInfo;
}

//获取是否格挡
bool UBaseAbilitySystemLibrary::IsBlockedHit(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->IsBlockedHit();
	}
	return false;
}
//获取是否闪避
bool UBaseAbilitySystemLibrary::IsDodgeHit(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->IsDodgeHit();
	}
	return false;
}
//获取是否吸收
bool UBaseAbilitySystemLibrary::IsAbsorbHit(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->IsAbsorbHit();
	}
	return false;
}

//获取是否暴击
bool UBaseAbilitySystemLibrary::IsCriticalHit(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->IsCriticalHit();
	}
	return false;
}
//获取是否硬直
bool UBaseAbilitySystemLibrary::IsStagger(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->IsStagger();
	}
	return false;
}
//获取硬直值
float UBaseAbilitySystemLibrary::GetStagger(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->GetStagger();
	}
	return 0.f;
}

//获取伤害类型
FGameplayTag UBaseAbilitySystemLibrary::GetDamageType(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		//判断如果存在，因为要解引用所以必须判断
		if (BaseEffectContext->GetDamageType().IsValid())
		{
			//返回解引用的标签
			return *BaseEffectContext->GetDamageType();
		}
	}
	return FGameplayTag();
}
//获取是否成功触发debuff
bool UBaseAbilitySystemLibrary::IsSuccessfulDebuff(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->IsSuccessfulDebuff();
	}
	return false;
}
//获取异常伤害
float UBaseAbilitySystemLibrary::GetDebuffDamage(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->GetDebuffDamage();
	}
	return 0.f;
}

float UBaseAbilitySystemLibrary::GetDebuffDuration(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->GetDebuffDuration();
	}
	return 0.f;
}

float UBaseAbilitySystemLibrary::GetDebuffFrequency(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->GetDebuffFrequency();
	}
	return 0.f;
}

FVector UBaseAbilitySystemLibrary::GetDeathImpulse(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->GetDeathImpulse();
	}
	return FVector::ZeroVector;
}

FVector UBaseAbilitySystemLibrary::GetKnockbackForce(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->GetKnockbackForce();
	}
	return FVector::ZeroVector;
}
//获取是否是径向衰减伤害
bool UBaseAbilitySystemLibrary::IsRadialDamage(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->IsRadialDamage();
	}
	return false;
}
//获取径向伤害内半径
float UBaseAbilitySystemLibrary::GetRadialDamageInnerRadius(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->GetRadialDamageInnerRadius();
	}
	return 0.f;
}
//获取径向伤害外半径
float UBaseAbilitySystemLibrary::GetRadialDamageOuterRadius(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->GetRadialDamageOuterRadius();
	}
	return 0.f;
}
//获取径向原点
FVector UBaseAbilitySystemLibrary::GetRadialDamageOrigin(const FGameplayEffectContextHandle& EffectContextHandle)
{
	if (const FBaseGameplayEffectContext* BaseEffectContext = static_cast<const FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->GetRadialDamageOrigin();
	}
	return FVector::ZeroVector;
}

//设置是否格挡
void UBaseAbilitySystemLibrary::SetIsBlockedHit(FGameplayEffectContextHandle& EffectContextHandle, bool bInIsBlockedHit)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetIsBlockedHit(bInIsBlockedHit);
	}
}
//设置是否闪避
void UBaseAbilitySystemLibrary::SetIsDodgeHit(FGameplayEffectContextHandle& EffectContextHandle, bool bInIsDodgeHit)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetIsDodgeHit(bInIsDodgeHit);
	}
}
//设置是否吸收
void UBaseAbilitySystemLibrary::SetIsAbsorbHit(FGameplayEffectContextHandle& EffectContextHandle, bool bInIsAbsorbHit)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetIsAbsorbHit(bInIsAbsorbHit);
	}
}

//设置是否暴击
void UBaseAbilitySystemLibrary::SetIsCriticalHit(FGameplayEffectContextHandle& EffectContextHandle,
	bool bInIsCriticalHit)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetIsCriticalHit(bInIsCriticalHit);
	}
}

void UBaseAbilitySystemLibrary::SetIsStagger(FGameplayEffectContextHandle& EffectContextHandle, bool bInIsStagger)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetIsStagger(bInIsStagger);
	}
}
//设置硬直值
void UBaseAbilitySystemLibrary::SetStagger(FGameplayEffectContextHandle& EffectContextHandle, float InStagger)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetStagger(InStagger);
	}
}

//设置伤害类型
void UBaseAbilitySystemLibrary::SetDamageType(FGameplayEffectContextHandle& EffectContextHandle, const FGameplayTag& InDamageType)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		//创建一个标签的共享指针
		const TSharedPtr<FGameplayTag> DamageType = MakeShared<FGameplayTag>(InDamageType);
		return BaseEffectContext->SetDamageType(DamageType);
	}
}
//设置是否成功触发debuff
void UBaseAbilitySystemLibrary::SetIsSuccessfulDebuff(FGameplayEffectContextHandle& EffectContextHandle, bool bInIsSuccessfulDebuff)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetIsSuccessfulDebuff(bInIsSuccessfulDebuff);
	}
}
//设置异常伤害
void UBaseAbilitySystemLibrary::SetDebuffDamage(FGameplayEffectContextHandle& EffectContextHandle, float InDebuffDamage)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetDebuffDamage(InDebuffDamage);
	}
}
//设置异常持续时间
void UBaseAbilitySystemLibrary::SetDebuffDuration(FGameplayEffectContextHandle& EffectContextHandle, float InDebuffDuration)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetDebuffDuration(InDebuffDuration);
	}
}
//设置异常频率
void UBaseAbilitySystemLibrary::SetDebuffFrequency(FGameplayEffectContextHandle& EffectContextHandle, float InDebuffFrequency)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetDebuffFrequency(InDebuffFrequency);
	}
}
//设置击杀敌人死亡是冲击方向向量
void UBaseAbilitySystemLibrary::SetDeathImpulse(FGameplayEffectContextHandle& EffectContextHandle, const FVector& InDeathImpulse)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetDeathImpulse(InDeathImpulse);
	}
}
//设置击退敌人方向向量
void UBaseAbilitySystemLibrary::SetKnockbackForce(FGameplayEffectContextHandle& EffectContextHandle, const FVector& InForce)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetKnockbackForce(InForce);
	}
}
//设置是否是径向伤害
void UBaseAbilitySystemLibrary::SetIsRadialDamage(FGameplayEffectContextHandle& EffectContextHandle, bool bInIsRadialDamage)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetIsRadialDamage(bInIsRadialDamage);
	}
}
//设置径向伤害内半径
void UBaseAbilitySystemLibrary::SetRadialDamageInnerRadius(FGameplayEffectContextHandle& EffectContextHandle, float InInnerRadius)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetRadialDamageInnerRadius(InInnerRadius);
	}
}
//设置径向伤害外半径
void UBaseAbilitySystemLibrary::SetRadialDamageOuterRadius(FGameplayEffectContextHandle& EffectContextHandle, float InOuterRadius)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetRadialDamageOuterRadius(InOuterRadius);
	}
}
//设置径向原点
void UBaseAbilitySystemLibrary::SetRadialDamageOrigin(FGameplayEffectContextHandle& EffectContextHandle, const FVector& InOrigin)
{
	if (FBaseGameplayEffectContext* BaseEffectContext = static_cast< FBaseGameplayEffectContext*>(EffectContextHandle.Get()))
	{
		return BaseEffectContext->SetRadialDamageOrigin(InOrigin);
	}
}

//获取指定一个原点，半径内所有存活的玩家或者AI控制的角色列表，可设置忽略对象,归类为 游戏玩法机制
//这个很重要 未来要用来实现 以自身为中心的AOE技能，教学是用来制作怪物的攻击范围判定
void UBaseAbilitySystemLibrary::GetLivePlayersWithinRadius(const UObject* WorldContextObject,
	TArray<AActor*>& OutOverlappingActors, const TArray<AActor*>& ActorsToIgnore, float Radius, const FVector& SphereOrigin)
{
	//设置球体碰撞参数
	FCollisionQueryParams SphereParams;
	//传入需要忽略的对象
	SphereParams.AddIgnoredActors(ActorsToIgnore);
	//获取重叠部分
	TArray<FOverlapResult> Overlaps;
	//获取世界
	if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
	{
		//在世界绘制重叠球体 设置球体原点、半径，把重叠部分返回到Overlaps中
		World->OverlapMultiByObjectType(Overlaps, SphereOrigin, FQuat::Identity, FCollisionObjectQueryParams(FCollisionObjectQueryParams::InitType::AllDynamicObjects), FCollisionShape::MakeSphere(Radius), SphereParams);
		//遍历Overlaps重叠数组
		for (FOverlapResult& Overlap : Overlaps)
		{
			//判断对象是否有战斗接口，判断是否存活
			if (Overlap.GetActor()->Implements<UCombatInterface>() && !ICombatInterface::Execute_IsDead(Overlap.GetActor()))
			{
				//把重叠对象添加到重叠数组
				OutOverlappingActors.AddUnique(ICombatInterface::Execute_GetAvatar(Overlap.GetActor()));
			}
		}
			
	}
}

//获取指定一个原点，矩形范围内所有存活的玩家或者AI控制的角色列表，可设置忽略对象,归类为 游戏玩法机制
void UBaseAbilitySystemLibrary::GetLivePlayersWithinBox(const UObject* WorldContextObject,
	TArray<AActor*>& OutOverlappingActors, const TArray<AActor*>& ActorsToIgnore, const FVector& BoxExtent, const FVector& BoxOrigin, const FRotator& BoxRotation)
{
	//设置盒体碰撞参数
	FCollisionQueryParams BoxParams;
	//传入需要忽略的对象
	BoxParams.AddIgnoredActors(ActorsToIgnore);
	//获取重叠部分
	TArray<FOverlapResult> Overlaps;
	//获取世界
	if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
	{
		//在世界绘制重叠盒体 设置盒体原点、范围、旋转，把重叠部分返回到Overlaps中
		World->OverlapMultiByObjectType(Overlaps, BoxOrigin, BoxRotation.Quaternion(), FCollisionObjectQueryParams(FCollisionObjectQueryParams::InitType::AllDynamicObjects), FCollisionShape::MakeBox(BoxExtent), BoxParams);
		//遍历Overlaps重叠数组
		for (FOverlapResult& Overlap : Overlaps)
		{
			//判断对象是否有战斗接口，判断是否存活
			if (Overlap.GetActor()->Implements<UCombatInterface>() && !ICombatInterface::Execute_IsDead(Overlap.GetActor()))
			{
				//把重叠对象添加到重叠数组
				OutOverlappingActors.AddUnique(ICombatInterface::Execute_GetAvatar(Overlap.GetActor()));
			}
		}
	}
}
//获取最近的目标 MaxTargets-最大目标数、Actors-需要计算的演员数组，OutClosestTargets-计算结果返回的数组，Origin-计算的原点
void UBaseAbilitySystemLibrary::GetClosestTargets(int32 MaxTargets, const TArray<AActor*>& Actors, TArray<AActor*>& OutClosestTargets, const FVector& Origin)
{
	//如果演员数组小于最大数量 直接返回
	if (Actors.Num() <= MaxTargets)
	{
		OutClosestTargets = Actors;
		return;
	}
	TArray<AActor*> ActorsToCheck = Actors;
	//目标计数器
	int32 NumTargetsFound = 0;
	while (NumTargetsFound < MaxTargets)
	{
		if (ActorsToCheck.Num() == 0) break;
		//用于存储最近距离
		double ClosestDistance = TNumericLimits<double>::Max();
		//存储最近演员
		AActor* ClosestActor = nullptr;
		for (AActor* PotentialTarget : ActorsToCheck)
		{
			//获取每个演员到原点的距离
			const double Distance = (PotentialTarget->GetActorLocation() - Origin).Length();
			//判断哪个演员的距离最小
			if (Distance < ClosestDistance)
			{
				ClosestDistance = Distance; //赋值最近距离
				ClosestActor = PotentialTarget; //赋值最近演员
			}
		}
		ActorsToCheck.Remove(ClosestActor); //移除循环演员
		OutClosestTargets.AddUnique(ClosestActor); //增加输出数组最近演员
		NumTargetsFound++;
	}
	//创建距离-演员对数组用于排序
	// TArray<TPair<double, AActor*>> DistanceActorPairs;
	// for (AActor* Actor : Actors)
	// {
	// 	const double Distance = (Actor->GetActorLocation() - Origin).Length();
	// 	DistanceActorPairs.Add(TPair<double, AActor*>(Distance, Actor));
	// }
	//
	// //按距离排序
	// DistanceActorPairs.Sort([](const TPair<double, AActor*>& A, const TPair<double, AActor*>& B)
	// {
	// 	return A.Key < B.Key;
	// });
	//
	// //取前MaxTargets个目标
	// for (int32 i = 0; i < MaxTargets && i < DistanceActorPairs.Num(); i++)
	// {
	// 	OutClosestTargets.Add(DistanceActorPairs[i].Value);
	// }
}

//判断攻击者和被攻击对象是否是盟友 这两个目标是否是盟友,用于敌人不能攻击敌人 或者 队友不能攻击队友
bool UBaseAbilitySystemLibrary::IsNotFriend(AActor* FirstActor, AActor* SecondActor)
{
	// 检查Actor是否仍然有效（未被销毁）
	if (!IsValid(FirstActor) || !IsValid(SecondActor))
	{
		// 如果任一Actor无效，返回true（不是朋友），避免访问已销毁的对象
		return true;
	}
	
	//玩家俩都为真 则说明是盟友
	const bool bBothArePlayers = FirstActor->ActorHasTag("Player") && SecondActor->ActorHasTag("Player");
	//敌人俩都为真 则说明是敌人
	const bool bBothAreEnemies = FirstActor->ActorHasTag("Enemy") && SecondActor->ActorHasTag("Enemy");
	//如果上述有一个不是真 说明就是敌人 无论哪个角度
	const bool bFriends = bBothArePlayers || bBothAreEnemies;
	return !bFriends;
}
//根据给定的 前向向量、轴向量、角度、发射数量，生成均匀分布的 <旋转器数组> 通用用于发射技能
TArray<FRotator> UBaseAbilitySystemLibrary::EvenlySpacedRotators(const FVector& Forward, const FVector& Axis, float Spread, int32 NumRotators)
{
	//旋转器数组
	TArray<FRotator> Rotators;
	//计算扩散角度
	const FVector LeftOfSpread = Forward.RotateAngleAxis(-Spread / 2.f, Axis);
	if (NumRotators > 1)
	{
		//计算投射物数量和角度等比 扩散增量 数量必须大于1时才计算
		const float DeltaSpread = Spread / (NumRotators - 1);
		//扩散角度算法
		for (int32 i = 0;i < NumRotators; i++)
		{
			//从左到右获取当前随从对应的线条位置
			const FVector Direction = LeftOfSpread.RotateAngleAxis(i * DeltaSpread, FVector::UpVector);
			Rotators.Add(Direction.Rotation());
		}
	}
	else
	{
		Rotators.Add(Forward.Rotation());
	}
	return Rotators;
	
}
//根据给定的 前向向量、轴向量、角度、发射数量，生成均匀分布的 <方向向量数组> 通用用于发射技能
TArray<FVector> UBaseAbilitySystemLibrary::EvenlySpacedVectors(const FVector& Forward, const FVector& Axis, float Spread, int32 NumVectors)
{
	//旋转器数组
	TArray<FVector> Vectors;
	//计算扩散角度
	const FVector LeftOfSpread = Forward.RotateAngleAxis(-Spread / 2.f, Axis);
	if (NumVectors > 1)
	{
		//计算投射物数量和角度等比 扩散增量 数量必须大于1时才计算
		const float DeltaSpread = Spread / (NumVectors - 1);
		//扩散角度算法
		for (int32 i = 0;i < NumVectors; i++)
		{
			//从左到右获取当前随从对应的线条位置
			const FVector Direction = LeftOfSpread.RotateAngleAxis(i * DeltaSpread, FVector::UpVector);
			//方向直接赋值项链 不需要.出Rotation旋转器
			Vectors.Add(Direction);
		}
	}
	else
	{
		Vectors.Add(Forward);
	}
	return Vectors;
}

//根据怪物职业角色和等级，获取当前怪物的修为值对应ct表奖励
int32 UBaseAbilitySystemLibrary::GetXPRewardForClassAndLevel(const UObject* WorldContextObject,
	ECharacterClass CharacterClass, int32 CharacterLevel)
{
	//获取类型数据类
	UCharacterClassInfo* CharacterClassInfo = GetCharacterClassInfo(WorldContextObject);
	if (CharacterClassInfo == nullptr) return 0;
	//从CT表中读取对应等级的修为值返回
	const FCharacterClassDefaultInfo Info = CharacterClassInfo->GetCharacterClassDefaultInfo(CharacterClass);
	const float XPReward = Info.XPReward.GetValueAtLevel(CharacterLevel);
	return static_cast<int32>(XPReward);
}
//根据怪物职业角色和等级，获取当前怪物的灵气值对应ct表奖励
int32 UBaseAbilitySystemLibrary::GetLingQiRewardForClassAndLevel(const UObject* WorldContextObject,
	ECharacterClass CharacterClass, int32 CharacterLevel)
{
	//获取类型数据类
	UCharacterClassInfo* CharacterClassInfo = GetCharacterClassInfo(WorldContextObject);
	if (CharacterClassInfo == nullptr) return 0;
	//从CT表中读取对应等级的灵气值返回
	const FCharacterClassDefaultInfo Info = CharacterClassInfo->GetCharacterClassDefaultInfo(CharacterClass);
	const float LingQiReward = Info.LingQiReward.GetValueAtLevel(CharacterLevel);
	return static_cast<int32>(LingQiReward);
}
//设置二段伤害目标的能力系统
void UBaseAbilitySystemLibrary::SetTargetAbilitySystemComponent(FDamageEffectParams& DamageEffectParams, UAbilitySystemComponent* InASC)
{
	//设置目标的能力系统组件
	DamageEffectParams.TargetAbilitySystemComponent = InASC;
}

//设置二段伤害径向伤害参数
void UBaseAbilitySystemLibrary::SetIsRadialDamageEffectParam(FDamageEffectParams& DamageEffectParams, bool bIsRadial, float InnerRadius, float OuterRadius, FVector Origin)
{
	DamageEffectParams.bIsRadialDamage = bIsRadial; //是否开启径向伤害
	DamageEffectParams.RadialDamageInnerRadius = InnerRadius; //径向伤害内半径
	DamageEffectParams.RadialDamageOuterRadius = OuterRadius; //径向伤害外半径
	DamageEffectParams.RadialDamageOrigin = Origin; //径向伤害原点
}
//设置二段伤害击退参数，Magnitude 默认0 如果不等于0 则使用传入的Magnitude计算击退
void UBaseAbilitySystemLibrary::SetKnockbackEffectParam(FDamageEffectParams& DamageEffectParams, FVector KnockbackDirection, float Magnitude)
{
	KnockbackDirection.Normalize();
	DamageEffectParams.KnockbackForce = KnockbackDirection * (Magnitude != 0.f ? Magnitude : DamageEffectParams.KnockbackForceMagnitude);
	
}
//设置二段伤害死亡冲击参数
void UBaseAbilitySystemLibrary::SetDeathImpulseEffectParam(FDamageEffectParams& DamageEffectParams, FVector ImpulseDirection, float Magnitude)
{
	ImpulseDirection.Normalize();
	DamageEffectParams.DeathImpulse = ImpulseDirection  * (Magnitude != 0.f ? Magnitude : DamageEffectParams.DeathImpulseMagnitude);
}

//应用伤害效果，异常伤害等
FGameplayEffectContextHandle UBaseAbilitySystemLibrary::ApplyDamageEffect(const FDamageEffectParams& DamageEffectParams)
{
	//检查必要参数是否有效
	if (!DamageEffectParams.SourceAbilitySystemComponent || !DamageEffectParams.TargetAbilitySystemComponent || !DamageEffectParams.DamageGameplayEffectClass)
	{
		//这里打印一个日志显示有什么是空的
		UE_LOG(LogTemp, Error, TEXT("Invalid Parameter in ApplyDamageEffect"));
		return FGameplayEffectContextHandle();
	}
	
	const FBaseGameplayTags& GameplayTags = FBaseGameplayTags::Get();
	//从源技能系统组件中获取源角色
	const AActor* SourceAvatarActor = DamageEffectParams.SourceAbilitySystemComponent->GetAvatarActor();
	//从源能力系统组件中获取游戏效果上下文句柄
	FGameplayEffectContextHandle EffectContextHandle = DamageEffectParams.SourceAbilitySystemComponent->MakeEffectContext();
	//给效果上下文添加源对象
	EffectContextHandle.AddSourceObject(SourceAvatarActor);
	//设置硬直值
	SetStagger(EffectContextHandle,DamageEffectParams.Stagger);
	//设置击败敌人时的攻击向量 用于击飞敌人
	SetDeathImpulse(EffectContextHandle,DamageEffectParams.DeathImpulse);
	//设置击退力度
	SetKnockbackForce(EffectContextHandle,DamageEffectParams.KnockbackForce);
	
	//设置是否使用径向伤害
	SetIsRadialDamage(EffectContextHandle,DamageEffectParams.bIsRadialDamage);
	//设置是否使用径向伤害
	SetRadialDamageInnerRadius(EffectContextHandle,DamageEffectParams.RadialDamageInnerRadius);
	//设置是否使用径向伤害
	SetRadialDamageOuterRadius(EffectContextHandle,DamageEffectParams.RadialDamageOuterRadius);
	//设置是否使用径向伤害
	SetRadialDamageOrigin(EffectContextHandle,DamageEffectParams.RadialDamageOrigin);
	
	//创建游戏效果规格句柄
	const FGameplayEffectSpecHandle SpecHandle = DamageEffectParams.SourceAbilitySystemComponent->MakeOutgoingSpec(DamageEffectParams.DamageGameplayEffectClass,DamageEffectParams.AbilityLevel,EffectContextHandle);
	
	//检查规格句柄是否有效
	if (!SpecHandle.Data.IsValid())
	{
		return EffectContextHandle;
	}

	//通过异常伤害类型标签调用时 触发对应标签的 技能基础伤害 （这个就是技能伤害） 可以用这个去计算百分比
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,DamageEffectParams.DamageType,DamageEffectParams.BaseDamage);
	//通过异常触发概率标签 触发对应的概率
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Debuff_Chance,DamageEffectParams.DebuffChance);
	//通过异常伤害 触发伤害
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Debuff_Damage,DamageEffectParams.DebuffDamage);
	//通过异常持续时间 触发持续时间
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Debuff_Duration,DamageEffectParams.DebuffDuration);
	//通过异常频率 触发频率
	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle,GameplayTags.Debuff_Frequency,DamageEffectParams.DebuffFrequency);
	 
	// 这个是循环多种伤害类型的写法,如果用循环写法就要重构一下 DamageEffectParams 里的伤害和异常伤害 现在是单一的，需要弄成一个 数组
	// for (TPair<FGameplayTag, FScalableFloat>& Pair : DamageTypes)
	// {
	// 	//从游戏标签获取获取能力等级
	// 	const float ScaledDamage = Pair.Value.GetValueAtLevel(GetAbilityLevel());
	// 	UAbilitySystemBlueprintLibrary::AssignTagSetByCallerMagnitude(SpecHandle, Pair.Key,ScaledDamage);
	// }
	//从参数中获取目标技能系统组件，并调用应用游戏效果到自身（目标身上）
	DamageEffectParams.TargetAbilitySystemComponent->ApplyGameplayEffectSpecToSelf(*SpecHandle.Data);
	return EffectContextHandle;
}

//智能目标选择和转向 - 优先使用传入的目标，如果没有则尝试获取玩家选中的目标，并让玩家转向目标
FVector UBaseAbilitySystemLibrary::RotatePlayerToTarget(AActor* SourceAvatarActor, AActor* TargetActor, FVector& TargetLocation, float ToleranceDegrees)
{
	if (!SourceAvatarActor || !TargetActor)
	{
		return FVector::ZeroVector;
	}

	// 计算角色当前位置和目标位置
	const FVector PlayerLocation = SourceAvatarActor->GetActorLocation();
	const FVector ActualTargetLocation = TargetActor->GetActorLocation();
	
	// 计算方向向量和旋转
	const FVector DirectionToTarget = (ActualTargetLocation - PlayerLocation).GetSafeNormal();
	const FRotator ToTargetRotation = DirectionToTarget.Rotation();
	
	// 检查是否需要旋转（基于容差角度）
	const FRotator CurrentRotation = SourceAvatarActor->GetActorRotation();
	const float DeltaYaw = FMath::Abs(FMath::FindDeltaAngleDegrees(CurrentRotation.Yaw, ToTargetRotation.Yaw));
	
	if (DeltaYaw > ToleranceDegrees)
	{
		// 只设置Yaw，保持水平转向，不改变Pitch和Roll
		SourceAvatarActor->SetActorRotation(FRotator(0.f, ToTargetRotation.Yaw, 0.f));
	}
	
	// 更新传入的目标位置引用并返回
	TargetLocation = ActualTargetLocation;
	return ActualTargetLocation;
}

bool UBaseAbilitySystemLibrary::GetSmartTargetAndRotatePlayer(const UObject* WorldContextObject, AActor* SourceAvatarActor, AActor* InputTarget, const FVector& DefaultTargetLocation, AActor*& OutFinalTarget, FVector& OutFinalTargetLocation)
{
	// 初始化输出参数
	OutFinalTarget = InputTarget;
	OutFinalTargetLocation = DefaultTargetLocation;
	
	// 如果传入的目标有效且实现了战斗接口，直接使用
	if (InputTarget && InputTarget->Implements<UCombatInterface>())
	{
		OutFinalTargetLocation = InputTarget->GetActorLocation();
		return true;
	}
	
	// 如果没有有效的传入目标，尝试获取玩家选中的目标
	// 通过 WorldContextObject 获取对应的 AbilitySystemComponent，然后获取其 AvatarActor
	if (SourceAvatarActor)
	{
		AActor* SelectedTarget = IPlayerInterface::Execute_GetSelectedTarget(SourceAvatarActor);
		if (SelectedTarget && SelectedTarget->Implements<UCombatInterface>())
		{
			// 新增：若目标已死亡，则清空选中目标并回退到默认位置（鼠标位置）
			if (ICombatInterface::Execute_IsDead(SelectedTarget))
			{
				IPlayerInterface::Execute_ClearSelectedTarget(SourceAvatarActor);
				OutFinalTarget = nullptr;
				OutFinalTargetLocation = DefaultTargetLocation;
				return false;
			}

			// 获取目标位置
			const FVector TargetLocation = SelectedTarget->GetActorLocation();
					
			// 让玩家角色转向面对目标
			const FVector PlayerLocation = SourceAvatarActor->GetActorLocation();
			const FVector DirectionToTarget = (TargetLocation - PlayerLocation).GetSafeNormal();
			const FRotator NewRotation = DirectionToTarget.Rotation();
			SourceAvatarActor->SetActorRotation(FRotator(0.f, NewRotation.Yaw, 0.f)); // 只设置Yaw，保持水平转向
					
			// 更新输出参数
			OutFinalTarget = SelectedTarget;
			OutFinalTargetLocation = TargetLocation;
			return true;
		}
	}
	// 如果都没有找到有效目标，返回false，使用默认位置
	return false;
}
// bNeedTarget-是否需要指向敌人释放， bFindTarget-是否自动寻找敌人 ，bAutoLock-是否自动锁定, bDamageEffect-是否是伤害技能（如果是治疗技能可以给盟友用）
AActor* UBaseAbilitySystemLibrary::GetSelectedTargetFromAvatar(AActor* SourceAvatarActor, AActor* InputTarget, bool bNeedTarget, bool bFindTarget,bool bAutoLock, bool bDamageEffect)
{
	AActor* SelectedTarget = nullptr;
	//是否需要指向敌人释放 如果为true 就必须选中敌人才能释放
	// if (bNeedTarget)
	// {
	// 	if (bAutoLock)
	// 	{
	// 		if (IsValid(InputTarget) && SourceAvatarActor->Implements<UPlayerInterface>())
	// 		{
	// 			IPlayerInterface::Execute_SetSelectedTarget(SourceAvatarActor, InputTarget);
	// 		}
	// 	}
	// 	else
	// 	{
	// 		SelectedTarget = IPlayerInterface::Execute_GetSelectedTarget(SourceAvatarActor);
	// 		return SelectedTarget;
	// 	}
	// }
    // 1.1 具备战斗接口，直接返回
    if (IsValid(InputTarget) && InputTarget->Implements<UCombatInterface>())
    {
		// 新增：若目标已死亡，则清空选中目标并回退到默认位置（鼠标位置）
        if (ICombatInterface::Execute_IsDead(InputTarget))
        {
        	IPlayerInterface::Execute_ClearSelectedTarget(SourceAvatarActor);
        	return InputTarget;
        }
    	if (bAutoLock)
    	{
    		if (IsValid(InputTarget) && SourceAvatarActor->Implements<UPlayerInterface>())
    		{
    			IPlayerInterface::Execute_SetSelectedTarget(SourceAvatarActor, InputTarget);
    		}
    	}
        return InputTarget;
    }
    // 2) 若没有有效的输入目标，则尝试使用当前角色的锁定目标
    if (!IsValid(SourceAvatarActor)) return InputTarget;

    if (SourceAvatarActor->Implements<UPlayerInterface>())
    {
    	// 直接从PlayerState获取目标，避免客户端同步延迟
    	// if (APawn* SourcePawn = Cast<APawn>(SourceAvatarActor))
    	// {
    	//     if (ABasePlayerState* PlayerState = SourcePawn->GetPlayerState<ABasePlayerState>())
    	//     {
    	//         SelectedTarget = PlayerState->GetSelectedTarget();
    	//         UE_LOG(LogTemp, Warning, TEXT("从PlayerState获取目标: %s"), 
    	//                SelectedTarget ? *SelectedTarget->GetName() : TEXT("NULL"));
    	//     }
    	// }
        SelectedTarget = IPlayerInterface::Execute_GetSelectedTarget(SourceAvatarActor);
    }

	if (IsValid(SelectedTarget) && SelectedTarget->Implements<UCombatInterface>())
	{
		//如果是盟友 并且是伤害类技能就返回 直接返回鼠标选择的目标,如果是治疗技能 可以用于队友
		if (!IsNotFriend(SourceAvatarActor,SelectedTarget) && bDamageEffect)
		{
			return InputTarget;
		}
		// 新增：若目标已死亡，则清空选中目标并回退到默认位置（鼠标位置）
		if (ICombatInterface::Execute_IsDead(SelectedTarget))
		{
			IPlayerInterface::Execute_ClearSelectedTarget(SourceAvatarActor);
			return InputTarget;
		}
		return SelectedTarget;
	}
    return InputTarget;
}

